package site.anxuan.seckill.controller;

import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import site.anxuan.seckill.common.BusinessException;
import site.anxuan.seckill.common.ErrorCode;
import site.anxuan.seckill.common.Results;
import site.anxuan.seckill.entity.Result;
import site.anxuan.seckill.common.Tools;
import site.anxuan.seckill.entity.User;
import site.anxuan.seckill.service.UserService;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@AllArgsConstructor
public class UserController {

    private final RedisTemplate<String, Object> redisTemplate;

    private final UserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result<String> login(String phone, String password) {
        if (!StringUtils.hasText(phone) || !StringUtils.hasText(password)) {
            throw new BusinessException(ErrorCode.USER_LOGIN_FAILED, "参数不合法");
        }
        User user = userService.login(phone, Tools.md5(password));
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("loginToken:" + token, user, 1, TimeUnit.DAYS);
        return Results.success(token);
    }

    /**
     * 登出
     */
    @GetMapping("/logout")
    public Result<Void> logout(String token) {
        redisTemplate.delete("loginToken:" + token);
        return Results.success();
    }

    @GetMapping("/otp/{phone}")
    public Result<String> getOTP(@PathVariable String phone) {
        String otp = this.generateOTP(phone);
        redisTemplate.opsForValue().set("otp:" + phone, otp);
        return Results.success(otp);
    }

    @PostMapping("/register")
    public Result<Void> register(String otp, User user) {
        String savedOtp = (String) redisTemplate.opsForValue().get("otp:" + user.getPhone());
        if (savedOtp == null || !savedOtp.equals(otp)) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "验证码错误！");
        }
        userService.register(user);
        return Results.success();
    }

    @GetMapping("/status")
    public Result<User> getUser(String token) {
        if (!StringUtils.hasText(token)) {
            throw new BusinessException(ErrorCode.USER_NOT_LOGIN, "参数不合法！");
        }
        User user = (User) redisTemplate.opsForValue().get("loginToken:" + token);
        return Results.success(user);
    }

    private String generateOTP(String phone) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            sb.append(new Random().nextInt(10));
        }
        return sb.toString();
    }

}
